﻿using Genersoft.Platform.Core.DataAccess;
using Genersoft.Platform.Core.Error;
using Genersoft.Platform.Security.SPI.SSOAuthentication;
using System;
using System.Data;
using System.IO;
using System.Web;
using System.Security.Cryptography;
using System.Net;
using System.Collections.Generic;
using Generalsoft.JT.FSSC.WebBillExtend;
using Genersoft.Platform.AppFramework.Service;
using System.Web.UI;
namespace Genersoft.JTGL.DDDL.Server
{
    public class SSOForInspur : IGSPSSOAuthenticator
    {

        #region GetSSOAuthenticationContext
        public GSPSSOAuthenticationContext GetSSOAuthenticationContext()//获取SSO身份验证上下文
        {
            ZTUserCodeContext context = new ZTUserCodeContext();
            string userToken = HttpContext.Current.Request["UserToken"];
            string appcode = HttpContext.Current.Request["AppCode"];
            context.TypeCode = "CASClient";
            context.AppCode = appcode;
            context.UserToken = userToken;
            return context;
        }
        #endregion

        #region AuthenticateUserIdentity
        /// <summary>
        /// 
        /// </summary>
        /// <add name="CASClient" Code="CASClient" AssemblyName="Genersoft.JTGL.DDDL.Server, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
        /// ImplClassName="Genersoft.JTGL.DDDL.Server.SSOForInspur" Description="接收用户Token 的 SSO方式" />
        /// <param name="context"></param>
        /// <returns></returns>
        public string AuthenticateUserIdentity(GSPSSOAuthenticationContext context)//验证用户身份
        {
            WriteLog("AuthenticateUserIdentity++++++++++++++++++++++++++++++");
            ZTUserCodeContext userCodeContext = context as ZTUserCodeContext;
            string userToken = userCodeContext.UserToken;
            WriteLog("userToken："+userToken);

            string encodeUrl1 = string.Empty;
            if (userToken.IndexOf("isdialog?") != -1)
            {
                encodeUrl1 = "http%3a%2f%2f10.55.8.46%2fcwbase%2fjtgl%2fSSO.aspx%3fisdialog%3d1";
                userToken = userToken.Substring(9, userToken.Length - 9);
            }
            else
            {
                encodeUrl1 = "http%3a%2f%2f10.55.8.46%2fcwbase%2fjtgl%2fsso.aspx";
            }

            string casServerUrlPrefix = "http://10.55.8.28:30080/cas/";
            WebClient web = new WebClient();
            string userCode = string.Empty;

            #region 获取蜂巢返回信息
            try
            {
                string url = casServerUrlPrefix + "validate?ticket=" + userToken + "&service=" + encodeUrl1;
                WriteLog("蜂巢地址：" + url);
                string response = web.DownloadString(url);
                WriteLog("验证返回的信息：" + response);
                StringReader reader = new StringReader(response);
                string isOk = reader.ReadLine();
                if (isOk.Trim() == "yes")
                {
                    userCode = reader.ReadLine();
                    WriteLog("userCode:" + userCode);
                }
                else
                {
                    throw new GSPException("Ticket验证失败", ErrorLevel.Warning);
                }

            }
            catch (Exception ex)
            {
                throw new GSPException("SSO出错" + ex.ToString());
            }
            #endregion

            #region 根据返回的userCode判断
            string userid = string.Empty;
            IGSPDatabase db = Database.GetDatabase(userCodeContext.AppCode);
            string sql = string.Format(@"select ID,AUTHCONTENT,STATE,LOCKTIME from GSPUser  where upper(Code)='{0}'", userCode.ToUpper());
            DataSet ds = db.ExecuteDataSet(sql);
            WriteLog("查询gspuser语句：" + sql);

            if (DataSetValidator.IsFirstDataTableHasRecord(ds))
            {
                DataRow dr = ds.Tables[0].Rows[0];
                if (Convert.ToString(dr["STATE"]).Trim() == "0")
                {
                    throw new GSPException("当前用户已被停用，如有异议，请联系管理员!", ErrorLevel.Warning);
                }
                userid = Convert.ToString(dr["ID"]);
            }
            else
            {
                throw new GSPException("单点认证失败，用户不存在!", ErrorLevel.Warning);
            }
            WriteLog("userid:" + userid);
            return userid;
            #endregion
        }

        #endregion

        #region WriteLog
        public static void WriteLog(string txt)
        {
            string strFilePath = @"c: \\LOG\\DDDL\\";
            if (!Directory.Exists(strFilePath))
                System.IO.Directory.CreateDirectory(strFilePath);
            string curDate = DateTime.Now.ToString("yyyyMMdd");
            strFilePath += "logfile" + curDate + ".log";
            string curtime = DateTime.Now.ToLongTimeString();
            System.IO.FileStream fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append);
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
            try
            {
                sw.WriteLine(curDate + "\n" + txt);
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
        }
        #endregion

    }


    #region   Class ZTUserCodeContext
    public class ZTUserCodeContext : GSPSSOAuthenticationContext
    {
        private string userToken = string.Empty;

        private string appCode = string.Empty;

        /// <summary>
        /// 用户编号
        /// </summary>
        public string UserToken
        {
            get
            {
                return this.userToken;
            }
            set
            {
                this.userToken = value;
            }
        }


        /// <summary>
        /// 实例编号
        /// </summary>
        public string AppCode
        {
            get
            {
                return this.appCode;
            }
            set
            {
                this.appCode = value;
            }
        }
    }
    #endregion

}
